package service

import (
	"gin/common"
	Mysql "gin/database"
	"gin/model"
	"gin/response"
	"gin/validate"
	"strings"
	"time"
)

var preloads = []string{"PlayRole.Role", "Action", "Shot", "Light", "LineMedia", "LineVideoMedia"}

func CreateEvent(Data validate.Event) (res model.Event, err error) {

	res.Name = Data.Name
	res.Type = Data.Type
	res.Param = Data.Param
	res.Sort = Data.Sort
	res.StoryId = Data.StoryId
	res.PlayId = Data.PlayId
	res.ActionId = Data.ActionId
	res.PlayRoleId = Data.PlayRoleId
	res.LineMediaId = Data.LineMediaId
	res.ShotId = Data.ShotId
	res.LightId = Data.LightId
	res.ActionText = Data.ActionText
	res.ShotText = Data.ShotText
	res.LineText = Data.LineText
	res.GroupId = Data.GroupId
	res.IsSendCommand = Data.IsSendCommand

	err = model.Insert(&res)

	// 新增事件 绑定group_id
	if res.GroupId > 0 {

		_, err := model.Update(&model.Event{}, map[string]interface{}{
			"eq": map[string]interface{}{
				"condition": "id = ?",
				"val":       res.GroupId,
			},
		}, map[string]interface{}{"group_id": res.GroupId})

		if err != nil {
			return res, err
		}
	}
	err = model.FindById(&res, res.Id, preloads)
	if err != nil {
		return res, err
	}
	return res, nil
}

func FindEvent(Param common.Filter) (resData model.Event, err error) {
	err = model.Find(&resData, Param.Filter, preloads)
	return resData, err
}

func SelectEvent(Param *common.SelectQueryParam) (int64, []model.Event, error) {
	var result response.SelectResp
	rows := []model.Event{}
	result.Rows = &rows

	err := model.Select(&model.Event{}, &result, Param.Filter.Filter, Param.Limit, Param.Offset, Param.Fields, Param.Order, preloads)

	return result.Total, rows, err
}

func UpdateEvent(eventId uint64, updateFields map[string]interface{}) (res model.Event, err error) {

	_, err = model.Update(&res, map[string]interface{}{
		"eq": map[string]interface{}{
			"condition": "id = ?",
			"val":       eventId,
		},
	}, updateFields)

	if err != nil {
		return res, err
	}

	err = model.FindById(&res, eventId, preloads)

	return res, err
}

func DeleteEvent(param *common.Filter) (int64, error) {
	return model.Delete(&model.Event{}, param.Filter)
}

// 阻塞查询任务状态
func QueryTaskStatus(mediaIdArray []uint64, maxTime int64) {
	starTime := time.Now().Unix()
	var medias []model.Media
	for {
		if time.Now().Unix()-starTime >= maxTime || len(mediaIdArray) == 0 {
			break
		}
		time.Sleep(time.Second * 1 / 2)

		result := Mysql.DB.Model(&model.Media{}).Find(&medias, mediaIdArray)

		if result.Error != nil {
			break
		}
		mediaIdArray = []uint64{}
		for _, mediaItem := range medias {
			if mediaItem.TaskResultFile == "" {
				mediaIdArray = append(mediaIdArray, mediaItem.Id)
			}
		}
	}
}

// 批量更新
func UpdateEventByFilter(param *common.Filter, updateFields map[string]interface{}) (res int64, err error) {
	db := Mysql.DB.Model(&model.Event{})
	// 组装过滤条件
	if param.Filter != nil {
		for key, val := range param.Filter {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	result := db.Updates(updateFields)

	if result.Error != nil {
		return 0, result.Error
	}
	return result.RowsAffected, nil
}
